<template>
  <n-modal
    v-model:show="getProps.modalData.show"
    class="custom-card"
    preset="card"
    :style="{ width: '600px' }"
    title="推广"
    :trap-focus="false"
    :bordered="false"
    :segmented="{
      content: true,
      footer: true
    }"
  >
    <n-space vertical class="content">
      <n-spin :show="qrcodeLoading">
        <n-space vertical align="center">
          <div class="qrcode">
            <img v-if="qrcode" class="qrcode__image" :src="qrcode" />
          </div>

          <n-button type="primary" size="small" @click="handleDownload">下载</n-button>
        </n-space>
      </n-spin>
    </n-space>
  </n-modal>
</template>

<script setup lang="ts">
  import { useStore } from '@/store'
  import { reactive, ref, watch } from 'vue'
  import { NModal, NSpin, NSpace, NButton } from 'naive-ui'
  import { saveAs } from 'file-saver'
  import { isProd } from '@/utils/is'

  const props = defineProps({
    modalData: {
      type: Object,
      default: () => ({})
    }
  })
  const store = useStore()
  const qrcodeLoading = ref(false)
  const qrcode = ref('')

  const getProps = reactive(props)
  watch(
    () => props.modalData.show,
    () => {
      if (props.modalData.show) {
        getQrcode()
      }
    }
  )

  async function getQrcode() {
    qrcodeLoading.value = true
    qrcode.value = ''
    const { data } = await store.dispatch('advertising/mpQrcode', {
      type: 1,
      path: props.modalData.path,
      appId: isProd ? null : 'wxdf9b01f4b35c7cb6'
    })
    qrcodeLoading.value = false
    qrcode.value = data
  }

  function handleDownload() {
    saveAs(qrcode.value, 'qrcode.png')
  }
</script>

<style scoped lang="scss">
  .qrcode {
    margin: 20px auto;
    width: 300px;
    height: 300px;
    &__image {
      width: 100%;
      height: 100%;
    }
  }
</style>
